import app.utils.System as sy
import json
import random
import string
import hashlib
from app.utils import Service, File


def PanelInstall(ROOT_PATH):
    system = sy.get_system_name()
    print("正在安装", system, "系统版本的面板...")
    print("请输入您的系统SSH信息:")
    ssh_name = input("您的系统SSH用户为: ")
    ssh_port = input("您的系统SSH端口为: ")
    ssh_pw = input("您的系统SSH密码为: ")
    # 写入文件
    json_data = {
        "ip": "127.0.0.1",
        "name": ssh_name,
        "port": ssh_port,
        "pw": ssh_pw
    }
    with open("./data/config/ssh.json", 'w') as file:
        json.dump(json_data, file)
    File.SetAuthority(ROOT_PATH + "/data/config/ssh.json", system)

    # 生成数据
    # 生成随机字母
    username = ''.join(random.choices(string.ascii_letters, k=5))
    pw = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
    port = random.randint(8888, 9000)
    ip = sy.get_system_ip()
    secret_key = ''.join(random.choices(string.ascii_letters + string.digits, k=9))
    # 生成随机安全入口
    safe_entry = ''.join(random.choices(string.ascii_letters, k=5))
    print("用户名:", username, "\n密码:", pw, "\n端口:", port, "\n安全入口:", safe_entry)
    print("面板访问地址: http://" + ip + ":" + str(port) + "/" + safe_entry)

    # 写入文件
    json_data = {
        username: hashlib.sha256(pw.encode()).hexdigest(),
        "port": port,
        "safe_entry": safe_entry,
        "secret_key": secret_key
    }
    with open("./data/config/panel.json", 'w') as file:
        json.dump(json_data, file)

    File.SetAuthority(ROOT_PATH + "/data/config/panel.json", system)

    # 设置开机自启动
    service_name = "QPanel_Service"

    service_file = Service.create_systemd_service(service_name)
    if service_file:
        return True
    else:
        return False
